<?php

namespace App\Model;

use App\Observers\UserObserver;
use http\Env\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use Spatie\Permission\Traits\HasRoles;

class Users extends BaseModel
{
    protected $connection = 'mysql';
    use HasRoles;
    protected $table = 'users';

    protected $fillable = ['name', 'password', 'api_token', 'desc'];

    protected $guard_name = 'web';
    private $fields = ['id', 'name', 'is_del', 'created_at', 'updated_at'];

    public static function findByToken(string $token)
    {
        return static::where(['api_token' => $token, 'is_del'=>0])->first();
    }

    public static function setRole($id, $role)
    {
        $user = Users::find($id);
        return $user->assignRole($role);
    }

    public function setPasswordAttribute($value)
    {
        $this->attributes['password'] = Hash::make($value);
    }

    /**
     * 重写管理员删除方法
     * @param array|\Illuminate\Support\Collection|int $id
     * @return int
     */
    public static function destroy($ids)
    {
        $ids = is_array($ids) ? $ids : func_get_args();

        $query = new Users();
        $res = $query -> whereIn('id', $ids)->update(['is_del' => 1, 'updated_at'=>date('Y-m-d H:i:s')]);
        return $res;
    }

    public static function generateApiToken()
    {
        return ['api_token' => Str::random(60)];
    }

    public function roomReport()
    {
        return $this->hasMany(RoomReport::class, 'user_id', 'user_id');
    }

    public function getList(Request $request)
    {
        $limit = $request->input('limit', 10);
        $page = $request->input('page', 1);
        $query = new Users();
        // todo 搜索
        return $query->with(['roles:id'])
            ->where('is_del', 0)
            ->paginate($limit, $this->fields, 'page', $page);
    }

    public function getAdmins()
    {
        $lists = DB::connection($this->connection)->table($this->table)->where('is_del', 0)->get(['id', 'name']);
        return $this->objToArray($lists);

    }


    public function getAdminByName(string $name)
    {
        return self::where('name', $name)->where('is_del', 0)->first();
    }

    public function getAllList($request = []){
        $limit = $request['limit'] ?? 10;
        $page = $request['page'] ?? 1;
        $is_del = $request['is_del'] ?? NULL;
        $query = new Users();
        // todo 搜索
        $query = $query->with(['roles:id']);
        if ( !is_null($is_del) ){
            $query = $query ->where('is_del', $is_del);
        }
        $data = $query ->paginate($limit,$this->fields,'page',$page);

            return $data;
    }


    public function getKkaudioUserTable($user_id = 0)
    {
//        $sql = "select * from zb_user where `is_del` = 0 and user_id = $user_id";
        $sql = "select * from zb_user where user_id = $user_id";
        return DB::connection('api')->select($sql);
    }

    public function getUserInfoByIds($userIds)
    {
        return DB::connection('api')->table('user')->whereIn('user_id', $userIds)->get(['user_id','uuid','nickname'])->toArray();
    }

    public function getUserInfoArrByIds($userIds)
    {
        $re = DB::connection('api')->table('user')->whereIn('user_id', $userIds)->get(['user_id','uuid','nickname', 'cp_status'])->toArray();
        return $this->objToArray($re);
    }

    /**
     * 根据uuids获取用户信息
     *
     * @param array $uuids
     * @return array
     */
    public function getUserInfoByUuids($uuids)
    {
        $result = DB::connection('api')->table('user')->whereIn('uuid', $uuids)->get(['user_id','uuid','nickname'])->toArray();

        return $this->objToArray($result);
    }


    /**
     * 读取当前登录的用户信息
     * @return mixed
     */
    public static function getCurrentUser()
    {
        $token = "";
        $tokenName = 'vue_admin_template_token';
        if (!empty($_COOKIE[$tokenName])) {
            $token = $_COOKIE[$tokenName];
        } elseif (!empty($_SERVER['HTTP_X_TOKEN'])) {
            $token = $_SERVER['HTTP_X_TOKEN'];
        }
        if (empty($token)) {
            return null;
        }
        $user = self::findByToken($token);
        return $user;
    }
}
